package sz.szsmk.citizencard.mvp.dzsmkpresenter;

import android.app.Service;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;

import com.google.gson.Gson;

import javax.inject.Inject;

import rx.functions.Action1;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.request.AccessTokenRequest;
import sz.szsmk.citizencard.model.network.bean.request.CardnoAuthorizationReq;
import sz.szsmk.citizencard.model.network.bean.request.CheckVirCakeBeanReq;
import sz.szsmk.citizencard.model.network.bean.request.IBaseRequest;
import sz.szsmk.citizencard.model.network.bean.request.QRCodeRequest;
import sz.szsmk.citizencard.model.network.bean.request.QueryAllCardsReq;
import sz.szsmk.citizencard.model.network.bean.request.UploadPic;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CardnoAuthorizationRes;
import sz.szsmk.citizencard.model.network.bean.response.CheckAcardRes;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.model.network.bean.response.CheckUserEcityRes;
import sz.szsmk.citizencard.model.network.bean.response.CheckVirCakeBeanRes;
import sz.szsmk.citizencard.model.network.bean.response.QRCodeBean;
import sz.szsmk.citizencard.model.network.bean.response.QuerLeisureCardsInfoRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryLeisureCardRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.ValidCardAuthorizationRes;
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThiedReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.req.QueryDzsmkAgreementReq;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.IdentityCodeMvpView;
import sz.szsmk.citizencard.retrofitrxjava.DZSmkAppInit;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.CommonUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.ObjectSignatureUtil;
import sz.szsmk.citizencard.widget.GlobalVariables;

public class IdentityCodePresenter extends AppBasePresenter<IdentityCodeMvpView> {
    NetworkDateSources mNetworkDateSource;
    private Handler mHandler;

    private boolean pauseRefresh = true;
    private boolean needRefreshCode = false;


    private Vibrator mVibrator;
    private int qrImgRefreshTime = 60;
    private final NetworkDateSource networkDateSource;
    private String openId;
    private String mobile;
    private int userId;


    @Inject
    public IdentityCodePresenter() {
        getComponent().inject(this);
        this.mNetworkDateSource = NetworkDateSources.getInstance();
        networkDateSource = NetworkDateSource.getInstance();
        mHandler = new Handler();
    }

    public void getQrNumber() {
        mVibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
        boolean hasNetwork = CommonUtils.hasNetwork(getActivity());
        if (!hasNetwork) {
            getMvpView().onGainQrCodeException("请检查您的网络");
        } else {
            QRCodeRequest qrCodeRequest = new QRCodeRequest();
            String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
            qrCodeRequest.setAccess_token(access_token);
            qrCodeRequest.setIs_fresh("1");
            mNetworkDateSource.getUserQRCode(qrCodeRequest, new SubscribeResult<QRCodeBean>() {
                @Override
                protected void onOk(QRCodeBean response) {
                    String json = new Gson().toJson(response);
                    L.e(Constant.TAG, "json---" + json);
                    handlerRefreshAndVibrator(qrImgRefreshTime);
                    getMvpView().success(response);
                }

                @Override
                protected void onFailure(QRCodeBean response) {
                    super.onFailure(response);
                    getMvpView().fail();
                }

                @Override
                protected void onNext(QRCodeBean response) {
                    super.onNext(response);
                }
            }, new ErrorAction() {
                @Override
                public void onCall(Throwable throwable) {
                    getMvpView().fail();
                }
            });
        }
    }

    private void handlerRefreshAndVibrator(int qrImgRefreshTime) {
        if (needRefreshCode) { //若需要刷新，则在这里计时
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自刷新
                    if (!pauseRefresh) {
                        //L.e(System.currentTimeMillis()+"---------------------------postDelayed里，马上刷新 "+pauseRefresh);

                        getQrNumber();
                    } else {
                        //L.e(System.currentTimeMillis()+"---------------------------postDelayed里，但不会去刷新 "+pauseRefresh);

                        //暂停了
                    }
                }
            }, qrImgRefreshTime * 1000);

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自刷新
                    if (!pauseRefresh) {
                        Log.e("IdentityCodePresenter", System.currentTimeMillis() + "---------------------------处理handlerVibrator ");
                        //振动
                        handlerVibrator();
                    }
                }
            }, qrImgRefreshTime * 1000 - 5000);
        }
    }

    private void handlerVibrator() {
        mVibrator.vibrate(1000); //直接振动1秒
        //mVibrator.vibrate(new long[]{1000, 1000}, -1);
    }

    public void queryAllcards() {
        QueryAllCardsReq queryAllCardsReq = new QueryAllCardsReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        queryAllCardsReq.setAccess_token(access_token);
        String json = new Gson().toJson(queryAllCardsReq);
        mNetworkDateSource.quryAllCards(queryAllCardsReq, new SubscribeResult<BaseBean>() {
            @Override
            protected void onOk(BaseBean response) {

            }

            @Override
            protected void onFailure(BaseBean response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void quryLeisureCards() {
        QueryAllCardsReq queryAllCardsReq = new QueryAllCardsReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        queryAllCardsReq.setAccess_token(access_token);
        String json = new Gson().toJson(queryAllCardsReq);
        mNetworkDateSource.quryLeisureCards(queryAllCardsReq, new SubscribeResult<QuerLeisureCardsInfoRes>() {
            @Override
            protected void onOk(QuerLeisureCardsInfoRes response) {
                getMvpView().queryLeisureSucc(response);
            }

            @Override
            protected void onFailure(QuerLeisureCardsInfoRes response) {
                super.onFailure(response);
                getMvpView().queryLeisureFail(response);

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }
    public void validCardAuthorization() {
        IBaseRequest baseRequest = new IBaseRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");

        baseRequest.setAccess_token(access_token);
        String json = new Gson().toJson(baseRequest);
        mNetworkDateSource.validCardAuthorization(baseRequest, new SubscribeResult<ValidCardAuthorizationRes>() {
            @Override
            protected void onOk(ValidCardAuthorizationRes response) {
                getMvpView().validCardAuthorizationSucc(response);
            }

            @Override
            protected void onFailure(ValidCardAuthorizationRes response) {
                super.onFailure(response);
                getMvpView().validCardAuthorizationFail(response);
            }

            @Override
            protected void onNext(ValidCardAuthorizationRes response) {
                super.onNext(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    public void checkUserEcity() {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        String json = new Gson().toJson(accessTokenRequest);
        mNetworkDateSource.checkUserEcity(accessTokenRequest, new SubscribeResult<CheckUserEcityRes>() {
            @Override
            protected void onOk(CheckUserEcityRes response) {
                getMvpView().checkUserEcitySucc(response);
            }

            @Override
            protected void onFailure(CheckUserEcityRes response) {
                super.onFailure(response);
                getMvpView().checkUserEcityFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void qurACard(String idCard) {
        QueryAllCardsReq queryAllCardsReq = new QueryAllCardsReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        queryAllCardsReq.setAccess_token(idCard);
        String json = new Gson().toJson(queryAllCardsReq);
        mNetworkDateSource.qurACard(queryAllCardsReq, new SubscribeResult<CheckAcardRes>() {

            @Override
            protected void onOk(CheckAcardRes response) {
                getMvpView().queryAcardSucc(response);
            }

            @Override
            protected void onFailure(CheckAcardRes response) {
                super.onFailure(response);
                getMvpView().queryAcardFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void cardnoAuthorization(String card) {
        CardnoAuthorizationReq cardnoAuthorizationReq = new CardnoAuthorizationReq();
        cardnoAuthorizationReq.setCard_no(card);
        cardnoAuthorizationReq.setType("1");
        String json = new Gson().toJson(cardnoAuthorizationReq);
        mNetworkDateSource.cardnoAuthorization(cardnoAuthorizationReq, new SubscribeResult<CardnoAuthorizationRes>() {
            @Override
            protected void onOk(CardnoAuthorizationRes response) {
                getQrNumber();
            }

            @Override
            protected void onFailure(CardnoAuthorizationRes response) {
                super.onFailure(response);
            }

        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }



    public void selectUserAuth() {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        mNetworkDateSource.selectUserAuth(accessTokenRequest, new SubscribeResult<SeleciUserAuthRes>() {
            @Override
            protected void onOk(SeleciUserAuthRes response) {
                getMvpView().selectUserAuthSucc(response);
            }

            @Override
            protected void onFailure(SeleciUserAuthRes response) {
                super.onFailure(response);
                getMvpView().selectUserAuthFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void getOpenId() {
        GetOpenIdReq getOpenIdReq = new GetOpenIdReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        getOpenIdReq.setUser_type(0);
        getOpenIdReq.setAccess_token(access_token);
        String s = new Gson().toJson(getOpenIdReq);

        L.e(Constant.TAG, "getOpenid----" + s);
        mNetworkDateSource.getOpenId(getOpenIdReq, new SubscribeResult<GetOpenIdRes>() {
            @Override
            protected void onOk(GetOpenIdRes response) {
                openId = response.getOpenId();
                mobile = response.getMobile();
                userId = response.getUserId();
                getMvpView().getOpenIdSucc(response);
            }

            @Override
            protected void onFailure(GetOpenIdRes response) {
                super.onFailure(response);
                getMvpView().getOpenIdFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void queryDzsmkAgreement(final String openId) {

//        ACache.get(DaggerApplication.getIns()).put("channelId", "000001");
        QueryDzsmkAgreementReq queryDzsmkAgreementReq = new QueryDzsmkAgreementReq();
        queryDzsmkAgreementReq.setOpenId(openId);
        queryDzsmkAgreementReq.setUserType(0);
        String json = new Gson().toJson(queryDzsmkAgreementReq);
        L.e(Constant.TAG, "queryDzsmkAgreement---->" + json);
        mNetworkDateSource.queryDzsmkAgreement(queryDzsmkAgreementReq, new SubscribeResult<QueryDzsmkAgreeMentRes>() {
            @Override
            protected void onOk(QueryDzsmkAgreeMentRes response) {
                String toJson = new Gson().toJson(response);
                String channelId = response.getChannelId();
                ACache.get(DaggerApplication.getIns()).put("channelId", channelId);
                L.e(Constant.TAG, "queryDzsmkAgreement---->" + toJson);
                getMvpView().queryDzsmkAgreementSucc(response, openId);
            }

            @Override
            protected void onFailure(QueryDzsmkAgreeMentRes response) {
                super.onFailure(response);
                getMvpView().queryDzsmkAgreementFail(response);
//                ((IRealNameContact.IRealNameView) mView).queryDzsmkAgreementFail(response);
                if (response.getCode().equals("000005")) {
                    ACache.get(DaggerApplication.getIns()).put("channelId", "000003");
//                    preAuthThird(openId, "2");
                }
//                ((IMainContact.IMainView) mView).queryDzsmkAgreementFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void checkIsOpenElecCard(String openId) {
        CommonRequest request = new CommonRequest();
        request.setOpenId(openId);
        ObjectSignatureUtil.signaturePreAuthRequest(request);
        String toJson = new Gson().toJson(request);
        L.e(Constant.TAG, "checkIsRealName------>" + toJson);
        networkDateSource.checkIsRealName(request, new Action1<CheckIsRealNameRes>() {
            @Override
            public void call(CheckIsRealNameRes preAuthRes) {
                String json = new Gson().toJson(preAuthRes);
                if (preAuthRes.getCode().equals("0000")) {
                    getMvpView().checkIsOpenElecCardSucc(preAuthRes);
//                    ((IRealNameContact.IRealNameView) mView).checkIsOpenElecCardSucc(preAuthRes);
                } else {
                    getMvpView().checkIsOpenElecCardFail(preAuthRes);
//                    ((IRealNameContact.IRealNameView) mView).checkIsOpenElecCardFail(preAuthRes);
                }
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    public void checkIsCharge() {
        CommonRequest commonRequest = new CommonRequest();
//        String openId = ACache.get(DaggerApplication.getIns()).getAsString("openId");
        commonRequest.setOpenId(openId);

        ObjectSignatureUtil.signatureZhsz(commonRequest, GlobalVariables.getInstance(DaggerApplication.getIns()).getPreAuthResult().getToken());
        String json = new Gson().toJson(commonRequest);
        L.e(Constant.TAG, "checkIsCharge-----" + json);
        networkDateSource.checkIsCharge(commonRequest, new Action1<CheckIsChargeRes>() {
            @Override
            public void call(CheckIsChargeRes ibaseBean) {
                String toJson = new Gson().toJson(ibaseBean);
                L.e(Constant.TAG, "checkIsCharge--->" + toJson);
//                ((IMainContact.IMainView) mView).checkIsChargeSucc(ibaseBean);
                getMvpView().checkIsChargeSucc(ibaseBean);
//                ((IRealNameContact.IRealNameView) mView).checkIsChargeSucc(ibaseBean);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
//                ((IMainContact.IMainView) mView).checkIsChargeFail();
            }
        });
    }

    public void preAuth() {
        PreAuthThiedReq preAuthThiedReq = new PreAuthThiedReq();
        preAuthThiedReq.setMobileNumber(mobile);
        preAuthThiedReq.setOpenId(openId);
        preAuthThiedReq.setUserId(userId + "");
        preAuthThiedReq.setPhotoUrl("");
        String channelId = ACache.get(DaggerApplication.getIns()).getAsString("channelId");
        preAuthThiedReq.setChannelId(channelId);

        ObjectSignatureUtil.signaturePreAuthRequest(preAuthThiedReq);
        String toJson = new Gson().toJson(preAuthThiedReq);
        L.e(Constant.TAG, "------->" + toJson);
        networkDateSource.preAuthThird(preAuthThiedReq, new Action1<PreAuthThirdRes>() {
            @Override
            public void call(PreAuthThirdRes preAuthRes) {
                String code = preAuthRes.getCode();
                if (code.equals("0000")) {
                    PreAuthThirdRes.DataBean data = preAuthRes.getData();
                    String json = new Gson().toJson(data);
                    ACache.get(DaggerApplication.getIns()).put("token", preAuthRes.getData().getToken());
                    PreAuthResult preAuthResult = new Gson().fromJson(json, PreAuthResult.class);
                    GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                    PreAuthResult authResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
                    String token = authResult.getToken();
                    getMvpView().preAuthSucc();
//                    ((IMainContact.IMainView) mView).preAuthThirdSucc(id);
                    L.e(Constant.MTAG, "存储的token：" + token);

                } else {
                    getMvpView().preAuthFail();
//                    ((IMainContact.IMainView) mView).preAuthThirdFail(preAuthRes);
                }


            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "--------------------" + throwable.getMessage());
            }
        });
    }

    public void upLoadPic(String cardNo, String photo){
        UploadPic uploadPic = new UploadPic();
        uploadPic.setCardNo(cardNo);
        uploadPic.setPhoto(photo);

        mNetworkDateSource.upLoadPic(uploadPic, new SubscribeResult<BaseBean>() {
            @Override
            protected void onOk(BaseBean response) {
                getMvpView().getUploadPic();
            }

            @Override
            protected void onNext(BaseBean response) {
                super.onNext(response);
            }

            @Override
            protected void onFailure(BaseBean response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    //查询是否开通
    public void getIsOpenPayCode(){
        CheckVirCakeBeanReq checkVirCakeBeanReq = new CheckVirCakeBeanReq();
        checkVirCakeBeanReq.setVirType(8000);
        checkVirCakeBeanReq.setAccessToken(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));
        mNetworkDateSource.getIsOpenPayCode(checkVirCakeBeanReq, new SubscribeResult<CheckVirCakeBeanRes>() {
            @Override
            protected void onOk(CheckVirCakeBeanRes response) {
                getMvpView().onIsOpenPayCodeSuccess(response);
            }

            @Override
            protected void onFailure(CheckVirCakeBeanRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

}
